package com.cdm.forum.service.impl;

import com.cdm.forum.common.Result;
import com.cdm.forum.common.ResultCode;
import com.cdm.forum.dao.UserMapper;
import com.cdm.forum.exception.ApplicationException;
import com.cdm.forum.model.User;
import com.cdm.forum.service.IUserService;
import com.cdm.forum.utils.MD5Util;
import com.cdm.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 注册
     *
     * @param user
     */
    @Override
    public void createUser(User user) {

        //参数检验
        if (user == null || StringUtils.isEmpty(user.getUsername())
                || StringUtils.isEmpty(user.getNickname())
                || StringUtils.isEmpty(user.getPassword())
                || StringUtils.isEmpty(user.getSalt())
        ) {
            //打印日志
            log.info(ResultCode.FAILED.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //查询用户信息
        User isUser = userMapper.selectByName(user.getUsername());
        if (isUser != null) {
            log.info(ResultCode.AILED_USER_EXISTS.toString());

            throw new ApplicationException(Result.failed(ResultCode.AILED_USER_EXISTS));
        }

        //新增用户,设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        //日期
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdateTime(now);

        //写入数据库
        int result = userMapper.insertSelective(user);
        if (result != 1) {
            //打印日志
            log.info(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_CREATE));
        }

        //操作成功，打印日志
        log.info("插入成功" + user);
    }

    /**
     * 查找是否有该用户名
     *
     * @param username
     * @return
     */
    @Override
    public User selectByName(String username) {
        //非空校验
        if (StringUtils.isEmpty(username)) {
            //打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //调用dao层
        User isUser = userMapper.selectByName(username);

        //非空校验
        if (isUser == null) {
            //打印日志
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        return isUser;
    }

    /**
     * 登陆验证
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {
        //参数校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //调用dao层
        User isUser = userMapper.selectByName(username);

        //非空校验
        if (isUser == null) {
            //打印日志
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //校验用户给的密码和数据库里面的是否一样
        //拿数据库的盐和密码生成密文
        String salt = isUser.getSalt();
        String newPassword = MD5Util.md5Salt(password, salt);
        //校验
        if (!newPassword.equals(isUser.getPassword())) {
            //打印日志
            log.info(ResultCode.FAILED_LOGIN.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_LOGIN));
        }
        return isUser;
    }

    /**
     * 查找改ID用户信息
     *
     * @param id
     * @return
     */
    @Override
    public User selectById(Long id) {
        if (id == null) {
            //打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO
        User user = userMapper.selectByPrimaryKey(id);

        return user;
    }

    /**
     * 更新用户发帖数
     *
     * @param id 用户id
     */
    @Override
    public void addOneArticleCountById(Long id) {
        //校验
        if (id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString()));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            //打印日志
            log.warn("{}board 的id:{}", ResultCode.ERROR_IS_NULL.toString(), id);
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.ERROR_IS_NULL.toString()));
        }

        //更新用户信息
        User newUser = new User();// 重新创建一个类是更新ArticleCount的值，如果在原来类上改会更新全部的值
        newUser.setId(user.getId());
        newUser.setArticleCount(user.getArticleCount() + 1);

        //执行dao
        int row = userMapper.updateByPrimaryKeySelective(newUser);

        if (row != 1) {
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }

    }

    @Override
    public void subOneArticleCountById(Long id) {
        //校验
        if (id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString()));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            //打印日志
            log.warn("{}board 的id:{}", ResultCode.ERROR_IS_NULL.toString(), id);
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.ERROR_IS_NULL.toString()));
        }

        //更新用户信息
        User newUser = new User();// 重新创建一个类是更新ArticleCount的值，如果在原来类上改会更新全部的值
        newUser.setId(user.getId());
        if (user.getArticleCount() - 1 <= 0) {
            newUser.setArticleCount(0);
        } else {
            newUser.setArticleCount(user.getArticleCount() - 1);
        }

        //执行dao
        int row = userMapper.updateByPrimaryKeySelective(newUser);

        if (row != 1) {
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
    }

    @Override
    public void modifyInfo(User user) {
        //1. 校验
        if (user == null || user.getId() == null || user.getId() <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //2. 查询用户是否存在
        User isUser = userMapper.selectByPrimaryKey(user.getId());
        if (isUser == null) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //3. 定义一个标注为
        boolean check = false;

        //定义一个更新对象, 防止传入的User对象设置其他用户是的属性
        User updataUser = new User();

        //4. 参数校验用户名
        updataUser.setId(user.getId());
        if (!StringUtils.isEmpty(user.getUsername())
                && !user.getUsername().equals(isUser.getUsername())) {
            //校验改的时候，判断改的用户名在数据库里面是否有
            User checkUser = userMapper.selectByName(user.getUsername());
            if (checkUser != null) {
                //打印日志
                log.warn(ResultCode.AILED_USER_EXISTS.toString());
                //抛出异常
                throw new ApplicationException(Result.failed(ResultCode.AILED_USER_EXISTS));
            }
            //数据库里面没有一样的用户，表示可以修改
            updataUser.setUsername(user.getUsername());
            //更新标志位
            check = true;
        }

        //5.参数校验昵称
        if (!StringUtils.isEmpty(user.getNickname())
                && !user.getNickname().equals(isUser.getNickname())) {
            //更新
            updataUser.setNickname(user.getNickname());
            //更新标志位
            check = true;
        }

        //6. 参数校验性别
        if (user.getGender() != null && isUser.getGender() != user.getGender()) {
            //更新
            updataUser.setGender(user.getGender());
            if(user.getGender() > 2 || user.getGender() < 0) {
                //更新
                updataUser.setGender((byte) 0);
            }

            //更新标志位
            check = true;
        }

        //7. 校验参数邮箱
        if (!StringUtils.isEmpty(user.getEmail())
                && !user.getEmail().equals(isUser.getEmail())) {
            //更新
            updataUser.setEmail(user.getEmail());
            //更新标志位
            check = true;
        }

        //校验参数电话号码
        if (!StringUtils.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(isUser.getPhoneNum())) {
            if (!isNumeric(user.getPhoneNum())) {
                //打印日志
                log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
                //抛出异常
                throw new ApplicationException("电话号码必须为数字");
            }
            if(user.getPhoneNum().length() != 11){
                //打印日志
                log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
                //抛出异常
                throw new ApplicationException("电话号码必须为11位");
            }
            //更新电话号码
            updataUser.setPhoneNum(user.getPhoneNum());
            //更新标志位
            check = true;
        }
        //8. 校验参数个人简介
        if (!StringUtils.isEmpty(user.getRemark())
                && !user.getRemark().equals(isUser.getRemark())) {
            //更新
            updataUser.setRemark(user.getRemark());
            //更新标志位
            check = true;
        }

        //更新标志位看看是否要更新
        if (check == false) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException("没有修改原来的内容");
        }

        //调用daoupdateByPrimaryKeySelective
        int row = userMapper.updateByPrimaryKeySelective(updataUser);
        if (row != 1) {
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
            //1.校验
        if (id <= 0 || id == null || StringUtils.isEmpty(newPassword) || StringUtils.isEmpty(oldPassword)) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //2.查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //3.校验老密码是否正确
        //对老密码加密
        String oldPwdSalt = MD5Util.md5Salt(oldPassword, user.getSalt());

        if(!oldPwdSalt.equals(user.getPassword())) {
            //打印日志
            log.warn(ResultCode.FAILED.toString());
            //抛出异常
            throw new ApplicationException("原密码错误");
        }

        //生成新的salt盐
        String salt = UUIDUtil.getUUID_32();
        //生成密文
        String newSaltPassword = MD5Util.md5Salt(newPassword, salt);

        //构造更新对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setPassword(newSaltPassword);
        updateUser.setSalt(salt);
        updateUser.setUpdateTime(new Date());

        //调用mapper
        int i = userMapper.updateByPrimaryKeySelective(updateUser);
        if (i != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(Result.failed(ResultCode.ERROR_SERVICES));
        }


    }

    /**
     * 判断字符串是否全部是数组
     */
    public boolean isNumeric(String str) {
        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c)) return false;
        }
        return true;
    }
}
